import {Divider, message} from 'antd';
import React, {useState, useRef} from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import CloneForm from './components/CloneForm';
import DeleteForm from './components/DeleteForm';
import {InstanceDelete, KInstance, KInstanceClone} from './data.d';
import {queryInstances, removeInstance, cloneInstance} from './service';

/**
 * 添加instance
 * @param fields
 */
const handleCloneInstance = async (fields: KInstanceClone) => {
  const hide = message.loading('正在复制环境...');
  try {
    await cloneInstance({ ...fields });
    hide();
    message.success('创建成功');
    return true;
  } catch (error) {
    hide();
    message.error('创建环境失败请重试！');
    return false;
  }
};

/**
 * 删除instance
 * @param fields
 */
const handleRemoveInstance = async (fields: InstanceDelete) => {
  const hide = message.loading('正在删除...');
  try {
    await removeInstance({
      ...fields
    });
    hide();
    message.success('删除成功');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败请重试！');
    return false;
  }
};

const TableList: React.FC<{}> = () => {
  const [cloneModalVisible, setCloneModalVisible] = useState<boolean>(false);
  const [deleteModalVisible, setDeleteModalVisible] = useState<boolean>(false);
  const [cloneValues, setCloneValues] = useState<KInstanceClone>({});
  const [deleteValues, setDeleteValues] = useState({});
  const actionRef = useRef<ActionType>();
  /*
  const [row, setRow] = useState<KConfigItem>();
  */

  const columns: ProColumns<KInstance>[] = [
    {title: 'id', dataIndex: 'id', hideInForm: true},
    {title: 'name', dataIndex: 'name', formItemProps: {rules: [{required: true, message:"环境名"}]}},
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a onClick={() => {
            setDeleteModalVisible(true);
            setDeleteValues({id: record.id, name: record.name});}}
          >删除</a>
          <Divider type="vertical" />
          <a onClick={() => {
            setCloneModalVisible(true);
            setCloneValues({oldName: record.name, newName: "", description: ""});}}
          >克隆</a>
        </>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<KInstance>
        actionRef={actionRef}
        rowKey="id"
        request={() => queryInstances()}
        columns={columns}
        search={false}
        options={false}
        pagination={false}
      />

      {cloneValues && Object.keys(cloneValues).length ? (
        <CloneForm
          onSubmit={async (value) => {
            const success = await handleCloneInstance(value);
            if (success) {
              setCloneModalVisible(false);
              setCloneValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            setCloneModalVisible(false);
            setCloneValues({});
          }}
          cloneModalVisible={cloneModalVisible}
          values={cloneValues}
        />
      ) : null}

      {deleteValues && Object.keys(deleteValues).length ? (
        <DeleteForm
          onSubmit={async (value) => {
            const success = await handleRemoveInstance(value);
            if (success) {
              setDeleteModalVisible(false);
              setDeleteValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            setDeleteModalVisible(false);
            setDeleteValues({});
          }}
          deleteModalVisible={deleteModalVisible}
          values={deleteValues}
        />
      ) : null}

    </PageContainer>
  );
};

export default TableList;
